<script lang="ts" setup>
import type { FieldsType } from '../../types';

import type { VxeGridListeners, VxeGridProps } from '#/adapter/vxe-table';

import { useVbenModal } from '@vben/common-ui';

import {
  Button,
  Image,
  message,
  Modal,
  Popconfirm,
  Space,
  Switch,
} from 'ant-design-vue';

import { useVbenVxeGrid } from '#/adapter/vxe-table';
import {
  deleteGuestbookFields,
  getGuestbookFields,
  postGuestbookFieldsListOrder,
  putGuestbookFieldsStatus,
} from '#/api/plugin/guestbook';
import Icon from '#/components/Icons';
import { toggleStatus } from '#/utils';

import DataFormModalView from './DataFormModal.vue';

const modalID = ref();
const [TableModal, modalApi] = useVbenModal();

const gridOptions: VxeGridProps<FieldsType> = {
  rowConfig: {
    useKey: true,
    drag: true,
  },
  columnConfig: {
    useKey: true,
  },
  columns: [
    { field: 'id', title: '编码', width: 120, dragSort: true },
    { field: 'title', title: '字段名称', treeNode: true },
    { field: 'name', title: '字段标识' },
    { field: 'type', title: '字段类型' },
    { field: 'status', title: '状态', slots: { default: 'status' } },
    {
      slots: { default: 'action' },
      field: 'action',
      fixed: 'right',
      title: '操作',
      width: 240,
    },
  ],
  treeConfig: {
    parentField: 'parentId',
    rowField: 'id',
    transform: true,
  },
  exportConfig: {},
  keepSource: true,
  proxyConfig: {
    ajax: {
      query: async ({ page }) => {
        const modalData = modalApi.getData();
        modalID.value = modalData.id;
        const { data } = await getGuestbookFields({
          page: page.currentPage,
          limit: page.pageSize,
          formid: modalData.id,
        });
        return data;
      },
    },
  },
  toolbarConfig: {
    custom: true,
    // export: true,
    // import: true,
    refresh: true,
    zoom: true,
  },
};

const [Grid, GridApi] = useVbenVxeGrid({
  gridOptions,
});

const gridEvents: VxeGridListeners<FieldsType> = {
  async rowDragend() {
    const visibleData = GridApi.grid.getTableData().visibleData;
    const result: { [key: string]: number } = {};
    // 使用 forEach 替代 reduce
    visibleData.forEach((item, index) => {
      result[item.id] = index;
    });
    await postGuestbookFieldsListOrder({ list_orders: result });
  },
};

const handleDelete = async (row: FieldsType) => {
  const $table = GridApi.grid;
  if ($table) {
    const { msg } = await deleteGuestbookFields({ ids: row.id });
    $table.remove(row);
    message.success(msg);
  }
};

const [DataFormModal, formModalApi] = useVbenModal({
  // 连接抽离的组件
  connectedComponent: DataFormModalView,
  onClosed() {
    const formModalData = formModalApi.getData();
    if (formModalData?.isUpdata) {
      GridApi.query();
    }
  },
});
const openDialog = async (title: '新增' | '编辑', row?: any | FieldsType) => {
  formModalApi.setState({
    title: `${title}数据`,
  });

  formModalApi.setData({ form: row, id: modalID.value });
  formModalApi.open();
};

const onChange = async (row: FieldsType) => {
  Modal.confirm({
    title: '系统提示',
    content: `确认要${row.status === 0 ? '停用' : '启用'}吗?`,
    async onOk() {
      try {
        await putGuestbookFieldsStatus({ id: row.id });
        message.success(`已${row.status === 0 ? '停用' : '启用'}`);
      } catch {
        row.status = toggleStatus(row.status);
      }
    },
    onCancel() {
      row.status = toggleStatus(row.status);
    },
  });
};
</script>
<template>
  <TableModal :footer="false" class="w-3/5">
    <DataFormModal />

    <Grid :grid-events="gridEvents" table-title="字段列表">
      <template #toolbar-tools>
        <Button class="mr-2" type="primary" @click="openDialog('新增')">
          <span class="anticon">
            <Icon icon="ri:add-line" />
          </span>
          新增字段
        </Button>
      </template>
      <template #image="{ row }">
        <Image v-if="row.image" :src="row.image" height="20" width="20" />
      </template>
      <template #status="{ row }">
        <Switch
          v-model:checked="row.status"
          :checked-value="1"
          :un-checked-value="0"
          checked-children="启用"
          un-checked-children="停用"
          @change="onChange(row)"
        />
      </template>
      <template #action="{ row }">
        <Space>
          <Button type="primary" @click="openDialog('编辑', row)">
            <template #icon>
              <span class="anticon">
                <Icon icon="ri:file-edit-line" />
              </span>
            </template>
            编辑
          </Button>
          <Popconfirm
            cancel-text="否"
            ok-text="是"
            title="确认删除？"
            @confirm="handleDelete(row)"
          >
            <Button danger type="primary">
              <template #icon>
                <span class="anticon">
                  <Icon icon="ri:delete-bin-line" />
                </span>
              </template>
              删除
            </Button>
          </Popconfirm>
        </Space>
      </template>
    </Grid>
  </TableModal>
</template>
